package frame.Customer;

import MyBatis.MyBatislianjian;
import frame.GuanliPanel;
import org.apache.ibatis.session.SqlSession;
import org.example.mapper.CustomerMapper;
import org.example.pojo.Customer;

import javax.swing.*;
import javax.swing.table.DefaultTableModel;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class customeradd extends JInternalFrame {
    private JTable table;
    private DefaultTableModel tableModel;
    private SqlSession sqlSession = MyBatislianjian.getSqlSession();
    private CustomerMapper customerMapper = sqlSession.getMapper(CustomerMapper.class);

    public customeradd() {
        // 设置内部窗口的标题和关闭方式
        setTitle("添加客户");
        setDefaultCloseOperation(JInternalFrame.DISPOSE_ON_CLOSE);

        // 创建表格模型和表格
        tableModel = new DefaultTableModel();
        table = new JTable(tableModel);

        // 添加表头
        String[] columnNames = {"客户编号", "公司名称", "公司简称", "公司地址", "公司电话", "公司邮件", "联系人姓名", "联系人电话", "备注"};
        tableModel.setColumnIdentifiers(columnNames);

        // 添加一行空白数据
        addEmptyRow();

        // 设置表格可编辑
        table.setEnabled(true);
        table.setAutoResizeMode(JTable.AUTO_RESIZE_ALL_COLUMNS);
        JScrollPane scrollPane = new JScrollPane(table);

        // 将表格添加到内部窗口的中心区域
        getContentPane().setLayout(new BorderLayout());
        getContentPane().add(scrollPane, BorderLayout.CENTER);

        // 添加按钮
        JButton addButton = new JButton("添加");
        addButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 提示用户确认添加
                int confirm = JOptionPane.showConfirmDialog(customeradd.this, "确认添加表格中的所有客户数据到数据库？", "确认", JOptionPane.YES_NO_OPTION);
                if (confirm == JOptionPane.YES_OPTION) {
                    // 提取表格数据并添加到数据库
                    List<Customer> customersToAdd = extractTableData();
                    if (customersToAdd != null && !customersToAdd.isEmpty()) {
                        boolean allValid = true;
                        Set<String> duplicateCids = new HashSet<>(); // 记录重复的客户编号
                        for (Customer customer : customersToAdd) {
                            // 检查关键字段不能为空
                            if (customer.getCid().isEmpty() || customer.getCcompanyName().isEmpty() || customer.getCcompanySName().isEmpty()
                                    || customer.getCcompanyAddress().isEmpty() || customer.getCName().isEmpty() || customer.getCtelPhone().isEmpty()) {
                                allValid = false;
                                break;
                            }
                            // 检查客户编号是否存在数据库中
                            if (isCustomerExists(customer.getCid())) {
                                duplicateCids.add(customer.getCid()); // 记录重复的客户编号
                            }
                        }

                        if (allValid) {
                            if (duplicateCids.isEmpty()) {
                                try {
                                    // 批量添加客户数据到数据库
                                    for (Customer customer : customersToAdd) {
                                        customerMapper.add(customer);
                                    }
                                    sqlSession.commit(); // 提交事务

                                    // 清空表格数据
                                    tableModel.setRowCount(0);
                                    addEmptyRow(); // 添加新的空行
                                    JOptionPane.showMessageDialog(customeradd.this, "成功添加 " + customersToAdd.size() + " 条客户数据到数据库！", "提示", JOptionPane.INFORMATION_MESSAGE);
                                } catch (Exception ex) {
                                    ex.printStackTrace();
                                    JOptionPane.showMessageDialog(customeradd.this, "添加客户数据时出现错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                                }
                            } else {
                                JOptionPane.showMessageDialog(customeradd.this, "表格中存在已经存在于数据库中的客户编号：" + duplicateCids, "错误", JOptionPane.ERROR_MESSAGE);
                            }
                        } else {
                            JOptionPane.showMessageDialog(customeradd.this, "每一行的客户编号、公司名称、公司简称、公司地址、联系人姓名、联系人电话都不能为空！", "错误", JOptionPane.ERROR_MESSAGE);
                        }
                    } else {
                        JOptionPane.showMessageDialog(customeradd.this, "表格中没有数据可以添加！", "提示", JOptionPane.WARNING_MESSAGE);
                    }
                }
            }
        });

        // 添加手动添加客户按钮
        JButton manualAddButton = new JButton("添加客户行");
        manualAddButton.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                // 添加新的空白行
                addEmptyRow();
            }
        });

        JButton addButton1 = new JButton("返回");
        addButton1.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                GuanliPanel.setContent(new CustomerPanel());
            }
        });
        // 将添加按钮和手动添加客户按钮添加到内部窗口的南部区域
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
        buttonPanel.add(addButton);
        buttonPanel.add(manualAddButton);
        buttonPanel.add(addButton1);
        getContentPane().add(buttonPanel, BorderLayout.SOUTH);

        // 设置内部窗口的大小和可见性
        setSize(800, 600);
        setVisible(true);
    }

    // 添加空白行到表格中
    private void addEmptyRow() {
        tableModel.addRow(new Object[]{"", "", "", "", "", "", "", "", ""});
    }

    // 提取表格数据的方法
    private List<Customer> extractTableData() {
        List<Customer> customers = new ArrayList<>();
        for (int row = 0; row < table.getRowCount(); row++) {
            String cid = (String) table.getValueAt(row, 0);
            String companyName = (String) table.getValueAt(row, 1);
            String companySName = (String) table.getValueAt(row, 2);
            String companyAddress = (String) table.getValueAt(row, 3);
            String companyPhone = (String) table.getValueAt(row, 4);
            String companyEmail = (String) table.getValueAt(row, 5);
            String contactName = (String) table.getValueAt(row, 6);
            String contactPhone = (String) table.getValueAt(row, 7);
            String other = (String) table.getValueAt(row, 8);

            // 创建 Customer 对象并添加到列表
            Customer customer = new Customer(cid, companyName, companySName, companyAddress, companyPhone, companyEmail, contactName, contactPhone, other);
            customers.add(customer);
        }
        return customers;
    }

    // 检查客户编号是否存在于数据库中
    private boolean isCustomerExists(String cid) {
        Customer customer = customerMapper.selectByCid(cid);
        return customer != null;
    }

}
